<template>
  <div class="dashboard-container">
        <el-row :gutter="20" class="data-overview">

    <el-col :span="12">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <div class="card-icon user-icon">
              <el-icon><User /></el-icon>
            </div>
            <div class="card-title">总用户数</div>
          </div>
          <div class="card-content">
            <div class="card-value">{{totalUser}}</div>
            <div class="card-trend positive">较上月增长 12.5%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <div class="card-icon active-icon">
              <el-icon><View /></el-icon>
            </div>
            <div class="card-title">活跃用户</div>
          </div>
          <div class="card-content">
            <div class="card-value">{{activeUsers}}</div>
            <div class="card-trend positive">较上月增长 8.3%</div>
          </div>
        </el-card>
      </el-col>
       </el-row>
    <!-- 模式选择器 -->
    <el-select 
      v-model="selectedMode" 
      placeholder="选择模式" 
      size="large" 
      class="mode-selector"
    >
      <el-option 
        v-for="mode in modes" 
        :key="mode.gamenumber" 
        :label="mode.gameName" 
        :value="mode.gamenumber"
      ></el-option>
    </el-select>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="data-overview">
      
      <el-col :span="12">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <div class="card-icon complete-icon">
              <el-icon><Medal /></el-icon>
            </div>
            <div class="card-title">培训完成率</div>
          </div>
          <div class="card-content">
            <div class="card-value">{{completionRate}}</div>
            <div class="card-trend positive">较上月提升 {{completionRateTrend}}%</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="data-card">
          <div class="card-header">
            <div class="card-icon score-icon">
              <el-icon><StarFilled /></el-icon>
            </div>
            <div class="card-title">平均分数</div>
          </div>
          <div class="card-content">
            <div class="card-value">{{averageScore}}</div>
            <div class="card-trend positive">较上月提升 {{averageScoreTrend}} 分</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>能力分布</span>
              <el-button size="small" type="primary" plain @click="exportData">
                <el-icon><Download /></el-icon>导出数据
              </el-button>
            </div>
          </template>
          <div class="chart-container" id="ability-radar-chart"></div>
        </el-card>
      </el-col>
      <!-- <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>培训进度趋势</span>
              <el-radio-group v-model="selectdata" size="small">
                <el-radio-button :label="1">周</el-radio-button>
                <el-radio-button :label="2">月</el-radio-button>
                <el-radio-button :label="3">年</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container" id="training-trend-chart"></div>
        </el-card>
      </el-col> -->
    </el-row>

    <!-- 错误操作统计 -->
    <el-row :gutter="20" class="chart-section">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="chart-header">
              <span>高频错误操作统计</span>
            </div>
          </template>
          <div class="chart-container" id="error-stats-chart"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { API_BASE_URL } from '@/utils/constants'
import axios from 'axios'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      theoreticalKnowledge:0,
      averageDuration: 0,
      selectedMode: '',
      modes: [],
      completionRate: 89.2,
      completionRateTrend: 2.1,
      averageScore: 92.5,
      averageScoreTrend: 1.8,
      activeUsers: 856,
      selectdata: 1,
      totalUser: 0,
      errorStatsPeriod: '30days',
      yeardate: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      monthdate: ['1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日'],
      weekdate: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      trainingTrendChart: null,
      abilityRadarChart: null,
      errorStatsChart: null
    }
  },
  mounted() {
    this.initCharts()
    window.addEventListener('resize', this.handleResize)
    this.fetchModes()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    if (this.trainingTrendChart) this.trainingTrendChart.dispose()
    if (this.abilityRadarChart) this.abilityRadarChart.dispose()
    if (this.errorStatsChart) this.errorStatsChart.dispose()
  },
  methods: {
    initCharts() {
    this.initTrainingTrendChart()
    this.initAbilityRadarChart() // 使用雷达图
    this.initErrorStatsChart()
    },
    handleResize() {
      if (this.trainingTrendChart) this.trainingTrendChart.resize()
      if (this.abilityRadarChart) this.abilityRadarChart.resize()
      if (this.errorStatsChart) this.errorStatsChart.resize()
    },
    async fetchModes() {
      try {
        const response = await axios.get(`${API_BASE_URL}/game/list`)
        this.modes = response.data.data || []
        console.log('modes:', this.modes)
        if (this.modes.length > 0) {
          this.selectedMode = this.modes[0].gamenumber
          console.log('selectedMode:', this.selectedMode)
          this.fetchData()
        }
      } catch (error) {
        console.error('Error fetching modes:', error)
      }
    },
    async fetchModeData(modeId) {
      try {
         // 获取基础数据
        const response = await axios.get(`${API_BASE_URL}/game/${modeId}`)
        const data = response.data.data
        console.log('modeData:', data)
        this.completionRate = data.finishPercent
        // 新增：模式数据加载完成后刷新错误统计图表
  this.initErrorStatsChart();
        
      } catch (error) {
        console.error('Error fetching mode data:', error)
      }

// 获取平均分数（操作熟练度）
      try{
        const response2 = await axios.get(`${API_BASE_URL}/gamepass/${modeId}`)
        const data2 = response2.data.data
        data2.forEach(item => {
          this.averageScore += item.score
        })  
        console.log('averageScore:', this.averageScore)
        this.averageScore = this.averageScore / data2.length

        console.log('averageScore:', this.averageScore)
      }catch(error){
        console.error('Error fetching mode data:', error)
      }

    // 获取平均时长
      try{
        const response3 = await axios.get(`${API_BASE_URL}/datas/${modeId}`)
        const data3 = response3.data.data
        console.log('data3:', data3)
        this.averageDuration = data3.averageSeconds
        console.log('averageDuration:', this.averageDuration)
      }catch(error){
        console.error('Error fetching mode data:', error)
      }

    // 获取理论知识完成度
try{
  const response4 = await axios.get(`${API_BASE_URL}/user/users`)
  const data4 = response4.data.data
  console.log('data4:', data4)
  
  let sumKnowledge = 0
  data4.forEach(item => {
    try {
      // 处理可能的空值或无效数据
      console.log('item.safaDegree:', item.safeDegree)
      if (item.safeDegree && typeof item.safeDegree === 'string') {
        const cleanValue = item.safeDegree.replace('%', '').trim()
        const numericValue = parseFloat(cleanValue)
        console.log('numericValue:', numericValue)
        
        if (!isNaN(numericValue)) {
          sumKnowledge += numericValue
        }
      }
    } catch (e) {
      console.warn('Invalid safadegree value:', item.safaDegree)
    }
  })
  
  this.theoreticalKnowledge = sumKnowledge / data4.length
  console.log('theoreticalKnowledge:', this.theoreticalKnowledge)
}catch(error){
  console.error('Error fetching theoretical knowledge:', error)
}

          // 为雷达图准备数据
    const radarData = [
      { 
        value: [this.averageScore || 82, this.theoreticalKnowledge || 75, this.averageDuration || 65], 
        name: '用户能力' 
      }
    ]
    console.log('radarData:', radarData)
    this.initAbilityRadarChart(radarData)
    },
    async fetchData() {
      try {
        const response = await axios.get(`${API_BASE_URL}/user/users`)
        this.totalUser = response.data.data.length
        
        const activeResponse = await axios.get(`${API_BASE_URL}/user/active`)
        console.log('activeResponse:', activeResponse)
        this.activeUsers = activeResponse.data.data
        
        if (this.selectedMode) {
          await this.fetchModeData(this.selectedMode)
        }
      } catch (error) {
        console.error('Error fetching data:', error)
      }
      
    },

    // 其他图表初始化方法保持不变，但需要调整为使用 this 访问数据
    initTrainingTrendChart(trendData) {
      // ...实现保持不变，但使用 this.selectdata 等
    },
// 初始化能力雷达图
initAbilityRadarChart(radarData) {
  const chartDom = document.getElementById('ability-radar-chart')
  if (!chartDom) return
  
  if (this.abilityRadarChart) {
    this.abilityRadarChart.dispose()
  }
  
  this.abilityRadarChart = echarts.init(chartDom)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      left: 'center'
    },
    radar: {
      // 可以添加单位标识
indicator: [
  { name: '操作熟练度(分)', max: 100 },
  { name: '理论知识(分)', max: 100 },
  { name: '平均用时(秒)', yAxis: {
  min: 0,
  max: 3600,
  alignTicks: true,
  interval: 720  // 每 720 单位一个刻度（3600/5）
} }
],
      radius: '60%',
      center: ['50%', '45%'],
      alignTicks: false, // 解决刻度对齐问题
      splitNumber: 5
    },
    series: [
      {
        name: '用户能力分布',
        type: 'radar',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#8378ff' },
            { offset: 1, color: '#2a29e2' }
          ])
        },
        lineStyle: {
          width: 2,
          color: '#2a29e2'
        },
        data: radarData || [
          { value: [82, 75, 65], name: '用户能力' }
        ]
      }
    ]
  }
  
  this.abilityRadarChart.setOption(option)
},
async initErrorStatsChart() {
  console.log('开始加载错误统计数据，selectedMode:', this.selectedMode);
  if (!this.selectedMode) return;

  const url = `${API_BASE_URL}/operations/wrong/${this.selectedMode}`;
  console.log('请求URL:', url);

  try {
     const response = await axios.get(url);
    console.log('API响应:', response.data);
    
    if (response.data.code !== 1) throw new Error(response.data.message);
    
    const errorData = response.data.data;
    
    // 提取并处理数据：操作名称 + 错误率数值化
    const operationNames = errorData.map(item => item.operationName);
    const errorRates = errorData.map(item => 
      parseFloat(item.wrongPercent.replace('%', '').trim())
    );

    const chartDom = document.getElementById('error-stats-chart');
    if (!chartDom || !errorData.length) return;

    // 销毁旧实例（避免内存泄漏）
    if (this.errorStatsChart) this.errorStatsChart.dispose();
    
    this.errorStatsChart = echarts.init(chartDom);
    
    const option = {
      tooltip: { trigger: 'axis', formatter: '{b}: {c}%' },
      xAxis: {
        type: 'category',
        data: operationNames,
        axisLabel: { rotate: 0, interval: 0 } // 避免长文本重叠
      },
      yAxis: {
        type: 'value',
        name: '错误率 (%)',
        max: 100,
        axisLabel: { formatter: '{value}%' }
      },
      series: [{
        name: '错误率',
        type: 'bar',
        data: errorRates,
        itemStyle: { color: '#f56c6c' }
      }]
    };
    
    this.errorStatsChart.setOption(option);
  } catch (error) {
    console.error('ErrorStatsChart init failed:', error);
  }
},
    exportData() {
      // ...实现保持不变
    }
  },
  watch: {
    selectedMode(newVal) {
      console.log('selectedMode changed:', newVal)
      if (newVal) {
        this.fetchData()
      }
    },
    selectdata() {
      if (this.selectedMode) {
        this.fetchModeData(this.selectedMode)
        
      } else {
        this.initTrainingTrendChart()
      }
    },
    errorStatsPeriod() {
      this.initErrorStatsChart()
    }
  }
}
</script>
<style scoped>
.dashboard-container {
  padding: 10px;
}

.mode-selector {
  margin-bottom: 20px;
  width: 200px;
  float: right;
}

.data-overview {
  margin-bottom: 20px;
  clear: both;
}

.data-card {
  height: 120px;
  position: relative;
  overflow: hidden;
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.card-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  font-size: 20px;
  color: white;
}

.user-icon {
  background-color: #409EFF;
}

.active-icon {
  background-color: #67C23A;
}

.complete-icon {
  background-color: #E6A23C;
}

.score-icon {
  background-color: #F56C6C;
}

.card-title {
  font-size: 14px;
  color: #606266;
}

.card-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.card-trend {
  font-size: 12px;
}

.positive {
  color: #33800d;
}

.negative {
  color: #F56C6C;
}

.chart-section {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 0;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
  border-radius: 4px;
}
</style>